﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GameSchoolWeb.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using GameSchoolWeb.Models.ViewModels;
using System.Web.Security;

namespace GameSchoolWeb.Controllers
{
	[Authorize]
	public class CourseController : Controller
	{
		ICourseRepository m_courseRepository;
		IUserRepository m_userRepository;


		public CourseController()
		{
			m_courseRepository = new CourseRepository();
			m_userRepository = new UserRepository();
		}

		public CourseController(ICourseRepository courseRep)
		{
			m_courseRepository = courseRep;
		}

		public CourseController(IUserRepository userRep)
		{
			m_userRepository = userRep;
		}

		public ActionResult Index()
		{
			return View();
		}

		[HttpGet]
		public ActionResult GetAllCourses()
		{
			var courses = from m in m_courseRepository.Courses()
						  orderby m.strName ascending
						  select m;
			return View(courses);
		}

		[HttpGet]
		public ActionResult DefineLevels(int? id)
		{
			if (id == null) return View("NotFound");
			Level levelItem = new Level();
			levelItem.courseId = id.Value;

			var check = from c in m_courseRepository.Levels()
						where c.courseId == id.Value
						select c;

			if (check != null)
			{
				// athugað er hvort nú þegar sé búið að setja inn borð
				return View("AlreadyDefined");
			}


			return View(levelItem);
		}

		[HttpPost]
		public ActionResult DefineLevels(FormCollection formdata, int? id)
		{
			Level levelItem = new Level();
			UpdateModel(levelItem);
			levelItem.courseId = id.Value;
			int nNumberOfLevels = levelItem.nLvlNumber.Value;

			for (int i = 1; i <= nNumberOfLevels; i++)
			{
				/* sett eru inn í gagnagrunn nNumberOfLevels fjöldi borða
				fyrir núverandi námskeið */
				Level newlevelItem = new Level();
				newlevelItem.courseId = id.Value;
				newlevelItem.nLvlNumber = i;
				m_courseRepository.AddLevels(newlevelItem);
				m_courseRepository.Save();
			}

			return RedirectToAction("Details", new { id = levelItem.id });
		}

		/*
		 * Details eru nánari upplýsingar um námskeið sem valið er 
		 * og allt innihald þess.
		 */
		[HttpGet]
		public ActionResult Details(int? id)
		{
			if (id == null) return View("NotFound");

			// courseItem er námskeið sem valið er
			var courseItem = (from c in m_courseRepository.Courses()
							  where c.id == id
							  select c).SingleOrDefault();

			// newsItems eru allar fréttir fyrir núverandi námskeið.
			var newsItems = from n in m_courseRepository.NewsItems()
							where n.courseId == id
							select n;

			// levelItems er listi yfir öll borð sem núverandi námskeið hefur.
			var levelItems = from l in m_courseRepository.Levels()
							 where l.courseId == id
							 orderby l.nLvlNumber ascending
							 select l;

			CourseIndexModelView vm = new CourseIndexModelView(courseItem, newsItems, levelItems);

			return View(vm);

		}

		[HttpGet]
		public ActionResult GetCourses()
		{
			Guid UserGuid = (Guid)Membership.GetUser().ProviderUserKey;

			//model eru öll námskeið sem núverandi notandi er skráður í.
			var model = from c in m_courseRepository.Courses()
						join n in m_courseRepository.UserRegistrations() on c.id equals n.courseId
						where n.UserId == UserGuid
						orderby c.strName ascending
						select c;

			return View(model);
		}

		[HttpGet]
		public ActionResult GetLevel(int? id)
		{
			if (id == null) return View("NotFound");
			// levelItem er núverandi borð
			var levelItem = (from l in m_courseRepository.Levels()
							 where l.id == id
							 select l).SingleOrDefault();

			// lectureItems er listi af öllum fyrirlestrum í núverandi borði.
			var lectureItems = from l in m_courseRepository.Lecture()
							   where l.levelId == id
							   select l;

			// examItems er listi af öllum Prófum í núverandi borði.
			var examItems = from e in m_courseRepository.Exams()
							where e.levelId == id
							select e;

			LevelIndexModelView vm = new LevelIndexModelView(levelItem, lectureItems, examItems);

			return View(vm);
		}

		[HttpGet]
		public ActionResult EditCourse(int? id)
		{
			if (id == null) return View("NotFound");
			var course = (from c in m_courseRepository.Courses()
						  where c.id == id.Value
						  select c).SingleOrDefault();
			if (course != null)
			{
				return View(course);
			}
			return View("NotFound");
		}

		[HttpPost]
		public ActionResult EditCourse(FormCollection formdata, int? id)
		{
			var course = (from n in m_courseRepository.Courses()
						  where n.id == id.Value
						  select n).SingleOrDefault();

			if (course != null)
			{
				UpdateModel(course);
				m_courseRepository.Save();
				return RedirectToAction("Index", "Home");
			}
			return View("NotFound");
		}

		[Authorize(Roles = "Umsjonarmadur")]
		[HttpGet]
		public ActionResult CreateCourse()
		{
			return View(new Course());
		}

		[HttpPost]
		public ActionResult CreateCourse(FormCollection formdata)
		{
			Course courseItem = new Course();
			UpdateModel(courseItem);
			m_courseRepository.AddCourse(courseItem);
			m_courseRepository.Save();
			return RedirectToAction("GetAllCourses");
		}

		public ActionResult GetAllStudents()
		{
			return View();
		}

		[Authorize(Roles = "Umsjonarmadur")]
		[AcceptVerbs(HttpVerbs.Get)]
		public ActionResult EnrollStudent()
		{
			// courseItems eru allir kúrsar í gagnagrunni.
			var courseItems = from c in m_courseRepository.Courses()
							  orderby c.strName ascending
							  select new SelectListItem { Text = c.strName, Value = c.id.ToString() };

			// students eru allir nemendur í gagnagrunni.
			var students = from n in m_userRepository.Users()
						   join m in m_userRepository.UsersInRole() on n.UserId equals m.UserId
						   where m.RoleId.ToString() == "22a8fba3-dbcb-421c-8ed9-569052eb7cb1"
						   orderby n.UserName ascending
						   select new SelectListItem { Text = n.UserName, Value = n.UserId.ToString() };

			UserRegistration newStudent = new UserRegistration();

			UserRegistrationModelView mv = new UserRegistrationModelView(courseItems, students, newStudent);
			return View(mv);
		}

		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult EnrollStudent(FormCollection formdata)
		{
			UserRegistration newRegistration = new UserRegistration();
			UserRegistrationModelView vm = new UserRegistrationModelView();
			UpdateModel(vm);

			newRegistration.UserId = vm.studentId;
			newRegistration.courseId = vm.courseId;
			newRegistration.dRegistrationDate = DateTime.Now;


			var check = (from c in m_courseRepository.UserRegistrations()
						 where c.UserId == vm.studentId && c.courseId == vm.courseId
						 select c).SingleOrDefault();

			if (check == null)
			{
				//Athuga hvort nemandi sé nú þegar skráður í námskeiðið sem valið var.
				m_courseRepository.AddUserRegistration(newRegistration);
				m_courseRepository.Save();

				return RedirectToAction("EnrollStudent");
			}

			return View("StudentAlreadyEnrolled");
		}

		[HttpGet]
		public ActionResult EnrollTeacher()
		{
			// courseItems eru allir kúrsar í gagnagrunni.
			var courseItems = from c in m_courseRepository.Courses()
							  orderby c.strName ascending
							  select new SelectListItem { Text = c.strName, Value = c.id.ToString() };

			// teachers eru allir kennarar í gagnagrunni
			var teachers = from n in m_userRepository.Users()
						   join m in m_userRepository.UsersInRole() on n.UserId equals m.UserId
						   where m.RoleId.ToString() == "7d5996c6-7526-4598-acfe-ed3b2da68679"
						   orderby n.UserName ascending
						   select new SelectListItem { Text = n.UserName, Value = n.UserId.ToString() };

			UserRegistration newTeacher = new UserRegistration();
			UserRegistrationModelView vm = new UserRegistrationModelView(courseItems, teachers, newTeacher);

			return View(vm);
		}

		[HttpPost]
		public ActionResult EnrollTeacher(FormCollection formdata)
		{
			UserRegistration newRegistration = new UserRegistration();
			UserRegistrationModelView vm = new UserRegistrationModelView();
			UpdateModel(vm);
			newRegistration.UserId = vm.studentId;
			newRegistration.courseId = vm.courseId;
			newRegistration.dRegistrationDate = DateTime.Now;

			var check = (from c in m_courseRepository.UserRegistrations()
						 where c.UserId == vm.studentId && c.courseId == vm.courseId
						 select c).SingleOrDefault();

			if (check == null)
			{
				//Athuga hvort Kennari sé nú þegar skráður í námskeiðið sem valið var.
				m_courseRepository.AddUserRegistration(newRegistration);
				m_courseRepository.Save();

				return RedirectToAction("EnrollTeacher");
			}

			return View("TeacherAlreadyEnrolled");
		}

		[HttpGet]
		public ActionResult GetLevelList(Course courseItem)
		{
			// model er listi yfir öll borð í núverandi námskeiði.
			var model = from lvl in m_courseRepository.Levels()
						orderby lvl.nLvlNumber ascending
						where courseItem.id == lvl.courseId
						select lvl;

			return View(model);
		}

		[HttpGet]
		public ActionResult AddNews()
		{
			return View(new NewsItem());
		}

		[HttpPost]
		public ActionResult AddNews(FormCollection formdata, Course courseItem)
		{
			NewsItem newsItem = new NewsItem();
			newsItem.courseId = courseItem.id;
			UpdateModel(newsItem);
			m_courseRepository.AddNews(newsItem);
			m_courseRepository.Save();
			return RedirectToAction("Details", new { id = newsItem.courseId });
		}

	}
}
